import { useMemo, useState, useRef } from "react";
import styles from "./index.module.less";
import { getTableColumns, getSearchColumns, getCreateColumns } from "./constant";
import { Modal, message, Button, Upload, ColorPicker } from "antd";
import SuperTable from "@/components/SuperTable";
import cs from "classnames";
import { getRouteList, addRoute, editRoute, getDockList, deleteRoute, getPathByScID } from "@/api/modules/platform";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import useUrl from "@/hooks/useUrl";
import SearchBox from "@/components/SearchBox";
import { PlusOutlined, UploadOutlined } from "@ant-design/icons";
import { useRequest } from "ahooks";
import { getAllOrgList, getLocationTypeDict, getDictByCode } from "@/api/modules/dict";
import CreateForm from "@/components/CreateForm";
import { cloneDeep, omit } from "lodash";
import { store } from "@/store";
import { ProForm } from "@ant-design/pro-components";
import AMap from "@/components/AMap";

export default () => {
	const { navigate } = useUrl();
	const [params, setParams] = useState({});
	const [defaultValues, setDefaultValues] = useState<any>(null);
	const [addFile, setAddFile] = useState<any>(null);
	const [txtFile, setTxtFile] = useState<any>(null);
	const [routeColor, setRouteColor] = useState("#FF0000");
	
	// 新增：路线查看Modal相关状态
	const [routeModalVisible, setRouteModalVisible] = useState(false);
	const [routeData, setRouteData] = useState<any>(null);
	const [routePaths, setRoutePaths] = useState<any[]>([]);
	
	const createFormRef = useRef<any>(null);
	const dataTableRef = useRef<any>(null);
	const { data: orgList } = useRequest(() => getAllOrgList({ page: { pageNum: 1, pageSize: 100 }}));
	const { data: locationTypeList } = useRequest(() => getLocationTypeDict({ parentId: 0, code: 'COOR' }));
	const { data: areaTypeList } = useRequest(() => getDictByCode({ parentId: 0, code: 'AREA_TYPE' }));
	const { data: sceneList } = useRequest(() => getDockList({ page: { pageNum: 1, pageSize: 100 }}));

	const handleRequest = async (params: any, sortInfo: any) => {
		const paramsCopy = cloneDeep(params);
		const newParams = omit(paramsCopy, ["pageSize", "current"]);
		const requestData: any = {
			page: {
				pageSize: params.pageSize,
				pageNum: params.current
			},
			...newParams
		};

		const res = await getRouteList(requestData);
		return {
			total: res?.data?.total ?? 0,
			data: res?.data?.list ?? []
		};
	};

	const view = {
			label: "查看",
			value: "view"
		},
		edit = {
			label: "编辑",
			value: "edit"
		},
		deleteEnum = {
			label: "删除",
			value: "delete"
		};

	const newColumns = [
		...getTableColumns({ params, orgList, locationTypeList, areaTypeList  }),
		{
			title: "操作",
			width: 120,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "view":
						handleViewRoute(record);
						break;
					case "edit":
						handleShowCreateModel(record);
						break;
					case "delete":
						Modal.confirm({
							icon: null,
							title: "删除提示？",
							content: `确认删除${record?.scName}吗？`,
							closable: true,
							onOk: c => {
								deleteRoute({ id: record?.id }).then((res: any) => {
									if (res?.code === RESULT_CODES.SUCCESS) {
										message.success("删除成功");
										c?.();
										dataTableRef?.current?.reload();
									}
								});
							}
						});
						break;
				}
			},
			options: (record: any) => {
				return [view, edit, deleteEnum];
			}
		}
	];

	const NEW_SEARCH_COLUMNS = useMemo(() => {
		return getSearchColumns({sceneList, orgList});
	}, [sceneList, orgList]);
	
	const handleCreate = (formData: any, callBack?: () => void) => {
		if(!addFile || !txtFile) {
			message.error('请上传文件！')
			return
		}
		// 修复jsonValue构建逻辑，支持编辑时的文件数据
		const getFileUrl = (fileItem: any) => {
			// 如果是新上传的文件，从response.data中获取
			if (fileItem?.response?.data?.[0]) {
				return fileItem.response.data[0];
			}
			// 如果是编辑时的文件，优先从url字段获取，其次从name字段获取
			if (fileItem?.url) {
				return fileItem.url;
			}
			if (fileItem?.name) {
				return fileItem.name;
			}
			return '';
		};
		
		const jsonValue = {
			addFile: getFileUrl(addFile?.[0]) || '',
			txtFile: getFileUrl(txtFile?.[0]) || ''
		}
		
		// 添加调试信息，确保jsonValue正确构建
		console.log('构建的jsonValue:', jsonValue);
		console.log('addFile数据:', addFile?.[0]);
		console.log('txtFile数据:', txtFile?.[0]);
		
		const requestData = {
			...formData,
			files: JSON.stringify(jsonValue),
			color: routeColor
		}
		if(defaultValues) {
			editRoute({...requestData, id: defaultValues.id}).then((res: any) => {
				if(res.code === RESULT_CODES.SUCCESS) {
					message.success("路线更新成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 清空defaultValues，避免下次新增时回显编辑数据
					setDefaultValues(null);
					callBack && callBack();
				}
			})
		} else {
			addRoute(requestData).then((res: any) => {
				if(res.code === RESULT_CODES.SUCCESS) {
					message.success("路线创建成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 清空defaultValues，确保状态一致
					setDefaultValues(null);
					callBack && callBack();
				}
			})
		}
	}

	const handleShowCreateModel = (row: any) => {
		setDefaultValues(row || null);
		createFormRef?.current?.showModel();
		if(row) {
			// 解析文件信息，确保数据结构正确
			const filesData = JSON.parse(row?.files || '{}');
			setTxtFile([
				{
					name: filesData?.txtFile || "",
					uid: "2",
					status: "done",
					url: filesData?.txtFile || "" // 添加url字段用于显示
				}
			]);
			setAddFile([
				{
					name: filesData?.addFile || '',
					uid: '1',
					status: 'done',
					url: filesData?.addFile || '' // 添加url字段用于显示
				}
			]);
			setRouteColor(row?.color || '#FF0000')
		} else {
			onClearColorAndFile();
		}
	}

	const onClearColorAndFile = () => {
		setTxtFile(null)
		setAddFile(null)
		setRouteColor('#FF0000')
	}
	
	const CREATE_COLUMNS = useMemo(() => {
		return getCreateColumns({sceneList});
	}, [sceneList]);

	const handleSearch = (e: any) => {
		setParams(e);
	};

	// 处理查看路线
	const handleViewRoute = async (record: any) => {
		try {
			setRouteData(record);
			setRouteModalVisible(true);
			
			// 调用getPathByScID接口获取路线数据
			const res = await getPathByScID({ id: record.scId });
			if (res?.code === RESULT_CODES.SUCCESS) {
				// 处理整个res.data数组，每个元素都有自己的routeSubList和color
				const paths: any[] = [];
				res?.data?.forEach((routeItem: any) => {
					if (routeItem?.routeSubList) {
						routeItem.routeSubList.forEach((subItem: any) => {
							paths.push({
								path: JSON.parse(subItem.routeInfo),
								strokeColor: routeItem.color
							});
						});
					}
				});
				setRoutePaths(paths);
			} else {
				message.error("获取路线数据失败");
				setRoutePaths([]);
			}
		} catch (error) {
			console.error("获取路线数据失败:", error);
			message.error("获取路线数据失败");
			setRoutePaths([]);
		}
	};

	// 关闭路线查看Modal
	const handleCloseRouteModal = () => {
		setRouteModalVisible(false);
		setRouteData(null);
		setRoutePaths([]);
	};

	const handleChangeColor = (value: any) => {
		// 使用toHexString()方法获取HEX格式的颜色值
		const hexColor = value.toHexString();
		setRouteColor(hexColor);
	};

	return (
		<div className={styles.flexContainer}>
			{/* 路线查看Modal */}
			<Modal
				title={`查看路线 - ${routeData?.scName || ""}`}
				open={routeModalVisible}
				onCancel={handleCloseRouteModal}
				footer={null}
				width={800}
				centered
			>
				<div style={{ height: "500px", width: "100%" }}>
					<AMap polylinePaths={routePaths} mapStyle="blue"/>
				</div>
			</Modal>

			<CreateForm 
				title={defaultValues ? "编辑路线" : "创建路线"} 
				columns={CREATE_COLUMNS} 
				onCreate={handleCreate} 
				ref={createFormRef} 
				defaultValues={defaultValues}
			>
				<ProForm.Item label="txt文件" required>
					<Upload
						name="files"
						action={`${import.meta.env.VITE_API_URL}/api/system/uploadMultiple`}
						headers={{
							Authorization: store.getState().global.token
						}}
						fileList={txtFile}
						accept=".txt"
						onRemove={() => {
							setTxtFile(null)
						}}
						onChange={(info) => {
							if (info.file.status === 'done') {
								message.success(`${info.file.name}上传成功`);
								setTxtFile([info.file]);
							} else if (info.file.status === 'uploading') {
								setTxtFile([info.file]);
							} else if (info.file.status === 'error') {
								message.error(`${info.file.name}上传失败`);
								setTxtFile(null);
							}
						}}
					>
						<Button icon={<UploadOutlined />}>上传</Button>
					</Upload>
				</ProForm.Item>
				<ProForm.Item label="add文件" required>
					<Upload
						name="files"
						action={`${import.meta.env.VITE_API_URL}/api/system/uploadMultiple`}
						headers={{
							Authorization: store.getState().global.token
						}}
						fileList={addFile}
						accept=".add"
						onRemove={() => {
							setAddFile(null)
						}}
						onChange={(info) => {
							if (info.file.status === 'done') {
								message.success(`${info.file.name}上传成功`);
								setAddFile([info.file]);
							} else if (info.file.status === 'uploading') {
								setAddFile([info.file]);
							} else if (info.file.status === 'error') {
								message.error(`${info.file.name}上传失败`);
								setAddFile(null);
							}
						}}
					>
						<Button icon={<UploadOutlined />}>上传</Button>
					</Upload>
				</ProForm.Item>

				<ProForm.Item label="路线颜色" required>
					<ColorPicker value={routeColor} onChange={(value: any) => handleChangeColor(value)} />
				</ProForm.Item>
			</CreateForm>
			<div className={styles.rightModule}>
				<SearchBox columns={NEW_SEARCH_COLUMNS} onSearch={handleSearch} >
					<div></div>
				</SearchBox>
				<div
					className={cs({
						[styles.container]: true
					})}
				>
					<div className={styles.operation_group}>
						<Button icon={<PlusOutlined /> } type="primary" onClick={() => handleShowCreateModel(null)}>新增</Button>
						{/* <Button icon={<DeleteOutlined />} type="default">删除</Button> */}
					</div>
					<SuperTable
						params={{
							...params,
						}}
						ref={dataTableRef}
						// bordered
						rowKey="id"
						columns={newColumns}
						request={handleRequest}
						scroll={{ x: "900" }}
					/>
				</div>
			</div>

		</div>
	);
};
